package com.symaster.gameengine.test;

import com.symaster.common.swing.FpsManager;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferStrategy;

public class BufferStrategyDemo extends JFrame implements Runnable {
    private final Canvas canvas;
    private final FpsManager fpsManager;
    private boolean running = false;
    private int x = 0; // 矩形的x坐标

    public BufferStrategyDemo() {
        setTitle("BufferStrategy Demo");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        this.fpsManager = new FpsManager();

        // 创建一个画布
        canvas = new Canvas();
        canvas.setSize(800, 600);
        add(canvas);
        setVisible(true);
        canvas.createBufferStrategy(3); // 创建一个三重缓冲的 BufferStrategy
    }

    public void start() {
        running = true;
        Thread thread = new Thread(this);
        thread.start(); // 启动渲染线程
    }

    @Override
    public void run() {
        while (running) {
            render(); // 调用渲染方法
            update(); // 更新坐标

            fpsManager.paintWait(60); // 限制最大120fps

            // try {
            //     Thread.sleep(16); // 控制帧率（大约60FPS）
            // } catch (InterruptedException e) {
            //     e.printStackTrace();
            // }
        }
    }

    // 更新逻辑
    private void update() {
        final float speed = 20; // 每秒20

        x += 5;
        if (x > canvas.getWidth()) {
            x = 0; // 重置位置
        }
    }

    // 渲染逻辑
    private void render() {
        BufferStrategy bufferStrategy = canvas.getBufferStrategy();
        Graphics g = bufferStrategy.getDrawGraphics();

        // 清除屏幕
        g.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());

        // 绘制一个红色矩形
        g.setColor(Color.RED);
        g.fillRect(x, 50, 100, 100);

        // 释放图形对象
        g.dispose();

        // 显示缓冲内容
        bufferStrategy.show();

        // 同步刷新，防止撕裂
        // Toolkit.getDefaultToolkit().sync();
    }

    public static void main(String[] args) {
        BufferStrategyDemo demo = new BufferStrategyDemo();
        demo.start(); // 启动应用程序
    }
}
